#########################
#   Author : Leon yu    #
#   Date : 2025/06/13   #
#   Id : SM2772         #
#########################

# 报表-销售统计
from datetime import datetime
import pandas as pd
from dbResps import dc
from dbResps import storeId, Log
from bussinessApis import isNowDate


def getQueryStoreSalesReportFromDB(startTime:int, endTime:int):
    getQueryStoreSalesReport = dict()
    getQueryStoreSalesReport['ORDER_COUNT'] = 0
    getQueryStoreSalesReport['TURNOVER'] = 0
    getQueryStoreSalesReport['SALES_AMOUNT'] = 0
    getQueryStoreSalesReport['DISCOUNT_AMOUNT'] = 0
    getQueryStoreSalesReport['payChannelReportOrderCount'] = dict()
    getQueryStoreSalesReport['payChannelAmount'] = 0
    
    startTime2Date = datetime.strptime(dc.timestamp2Data(startTime), "%Y/%m/%d %H:%M:%S").strftime("%Y-%m-%d")
    endTime2Date = dc.timestamp2Data(endTime)
    tableName = 'order'
    where = f'store_id = "{storeId}" and `status` = \"SETTLED\" and settle_time like "{startTime2Date}%" and `status` = "SETTLED";'
    resp = dc.select(tableName=tableName, where=where)
    df = pd.DataFrame(resp)
    if df.shape[0] > 0:
        getQueryStoreSalesReport['ORDER_COUNT'] = df.shape[0]
        getQueryStoreSalesReport['TURNOVER'] = df['payable_amount'].sum(numeric_only=True)
        getQueryStoreSalesReport['SALES_AMOUNT'] = df['actual_amount'].sum(numeric_only=True)
        getQueryStoreSalesReport['DISCOUNT_AMOUNT'] = abs(df['discount_amount'].sum(numeric_only=True))
        getQueryStoreSalesReport['payChannelReportOrderCount'] = df.groupby(['sub_platform']).count()['payable_amount'].to_dict()
        getQueryStoreSalesReport['payChannelAmount'] = df['payable_amount'].sum(numeric_only=True)
        
    return getQueryStoreSalesReport

